import { login,logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 初始化数据（保存具体的数据）
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

// 修改state中的数据
const mutations = {
  SET_TOKEN:(state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
}

// 响应组件中用户的动作
const actions = {
  // 登录
  userLogin(context,userInfo){
    const { username, password } = userInfo
    
    return new Promise((resolve, reject) =>{
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        console.log(response)
        context.commit('SET_TOKEN',data.token)
        setToken(data.token)  //登录成功后将token存储在cookie之中
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登录用户信息
  getUserInfo({ commit, state}){
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        console.log(response)
        if(!data) {
          reject('Verification failed, please Login again.')
        }
        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出登录
  userLogout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN','')
        commit('SET_ROLES',[])
        removeToken()
        
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
